package com.dily.study.demo.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Date: 2022-08-10 星期三
 * Time: 13:37
 * Author: Dily_Su
 * Remark:
 */
public class TestLock {
    public static void main(String[] args) {
        BuyTicketLock ticketLock = new BuyTicketLock();

        new Thread(ticketLock).start();
        new Thread(ticketLock).start();
        new Thread(ticketLock).start();
    }
}

class BuyTicketLock implements Runnable{

    int ticketNums = 10;
    // 可重入锁
    private final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            lock.lock();
            try {
                if (ticketNums > 0){
                    System.out.println(ticketNums--);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    break;
                }
            }finally {
                lock.unlock();
            }
        }
    }
}